package com.example.demo.service;


import com.example.demo.entity.Student;
import com.example.demo.object.StudentQo;
import com.example.demo.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class StudentService {
    @Autowired
    private StudentRepository studentRepository;

    public Student findById(Long id){
        return studentRepository.findById(id).get();
    }

    public boolean save(Student student){
        try {
            studentRepository.save(student);
            return true;
        }catch (Exception e){
           e.printStackTrace();
           return false;
        }
    }

    public boolean deleteById(Long id){
        try {
            studentRepository.deleteById(id);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    public Page<Student> findAll(StudentQo studentQo){
        Sort sort = Sort.by(Sort.Direction.ASC, "id");
        Pageable pageable = PageRequest.of(studentQo.getPage(), studentQo.getSize(), sort);

        return studentRepository.findAll(new Specification<Student>(){
            @Override
            public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicatesList = new ArrayList<Predicate>();

                if(!StringUtils.isEmpty(studentQo.getId())) {
                    predicatesList.add(criteriaBuilder.equal(root.get("id"), studentQo.getId()));
                }

                if(!StringUtils.isEmpty(studentQo.getName())) {
                    predicatesList.add(criteriaBuilder.like(root.get("name"), "%" + studentQo.getName() + "%"));
                }

                query.where(predicatesList.toArray(new Predicate[predicatesList.size()]));

                return query.getRestriction();
            }
        }, pageable);
    }
}
